package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;

import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.uuid.UUIDUtil;
import com.aiti.lulian.constant.GxmhConstant;
import com.aiti.lulian.gxmh.dto.GxmhAppealParamDto;
import com.aiti.lulian.gxmh.dto.GxmhAppealQueryParamDto;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.entity.GxmhAppeal;
import com.aiti.lulian.gxmh.service.GxmhAppealService;
import com.aiti.lulian.gxmh.vo.GxmhAppealListItemVo;
import com.aiti.lulian.gxmh.vo.GxmhAppealVo;
import com.aiti.lulian.mapper.gxmh.GxmhAppealMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.utils.BusinessUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * description:
 * auth fcb
 * date 2025-06-12 15:34
 **/
@Service
@Slf4j
public class GxmhAppealServiceImpl extends BaseSerivceImpl<GxmhAppealMapper, GxmhAppeal> implements GxmhAppealService {


    @Autowired
    private GxmhSysMapper gxmhSysMapper;

    /**
     * 申诉部门列表，小程序端使用
     * @param queryDto
     * @return
     */
    public PageResult<GxmhAppealVo> queryAppealList(GxmhAppealQueryParamDto queryDto) {
        BusinessUtil.checkPageParam(queryDto);

        IPage<GxmhAppealVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhAppealVo> list = this.baseMapper.queryAppealList(page, queryDto);
        if(CollectionUtil.isNotEmpty( list)) {
            for(GxmhAppealVo vo : list) {
                // 当企业id和用户id都为空时是拨打电话，否则是查看名片,当科室职责不为空时，是查看详情
                if(StrUtil.isNotBlank(vo.getDuty())) {
                    vo.setType("detail");
                }else if(StrUtil.isEmpty(vo.getUserId())) {
                    vo.setType("phone");
                }else {
                    vo.setType("card");
                }
            }
        }
        PageResult<GxmhAppealVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 申诉部门列表，管理系统使用
     * @param queryDto
     * @return
     */
    public PageResult<GxmhAppealVo> queryAppealListForManage(GxmhAppealQueryParamDto queryDto) {
        BusinessUtil.checkPageParam(queryDto);
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(queryDto.getUserId());
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
            queryDto.setStreet(sysUserDto.getStreet());
        }
        IPage<GxmhAppealVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhAppealVo> list = this.baseMapper.queryAppealList(page, queryDto);
        PageResult<GxmhAppealVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 保存诉求
     * @param dto
     * @param loginUserId
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveAppeal(GxmhAppealParamDto dto, String loginUserId) {
        this.checkParam(dto);
        // 该条数据的所属区域
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginUserId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        this.checkAdminParam(dto, sysUserDto.getUsername());
        // 管理添加数据时区域在页面传递，非管理员时区域在用户信息中获取
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            dto.setProvince(sysUserDto.getProvince());
            dto.setCity(sysUserDto.getCity());
            dto.setCounty(sysUserDto.getRegion());
            dto.setStreet(sysUserDto.getStreet());
        }
        // 如果填写了用户名
        if(StrUtil.isNotEmpty(dto.getBusinessUsername())) {
            // 1. 查寻输入账号的userId
            SysUserDto sysUser = this.baseMapper.queryUserIdByUsername(dto.getBusinessUsername());
            if (sysUser == null) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】不存在");
            }
            GxmhAppeal appeal = new GxmhAppeal();
            appeal.setBaseId(UUIDUtil.getUUID());
            // 2. 查询输入账号绑定的企业
            String userEnterpriseId = this.baseMapper.queryEnterpriseIdByUserId(sysUser.getBaseId());
            if (StrUtil.isEmpty(userEnterpriseId)) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】未绑定企业");
            }
            // 3. 判断该企业是否是政府
            Integer zfCount = this.baseMapper.queryZFCountByEnterpriseId(userEnterpriseId);
            if (zfCount == 0) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】所属企业不是政府部门");
            }
            appeal.setEnterpriseId(userEnterpriseId);
            // 3. 查询该用户是否开通过名片
            Integer cardCount = this.baseMapper.queryCardountByUserId(sysUser.getBaseId());
            if (cardCount == 0) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】未开通名片");
            }
            appeal.setUserId(sysUser.getBaseId());
            appeal.setUserMobile(sysUser.getMobile());
            appeal.setDeptName(dto.getDeptName());
            appeal.setBusinessUsername(dto.getBusinessUsername());
            appeal.setBusinessPhone(dto.getBusinessPhone());
            appeal.setBaseCreateTime(new Date());
            appeal.setBaseCreateBy(loginUserId);
            appeal.setIsDelete(0);
            appeal.setBaseUpdateBy(loginUserId);
            appeal.setBaseUpdateTime(new Date());
            appeal.setProvince(dto.getProvince());
            appeal.setCity(dto.getCity());
            appeal.setCounty(dto.getCounty());
            appeal.setStreet(dto.getStreet());
            appeal.setDuty(dto.getDuty());
            appeal.setBusinessRealname(dto.getBusinessRealname());
            this.save(appeal);
        }
        else {
            GxmhAppeal appeal = new GxmhAppeal();
            appeal.setBaseId(UUIDUtil.getUUID());
            appeal.setBaseCreateTime(new Date());
            appeal.setBaseCreateBy(loginUserId);
            appeal.setBaseUpdateBy(loginUserId);
            appeal.setBaseUpdateTime(new Date());
            appeal.setIsDelete(0);
            appeal.setDeptName(dto.getDeptName());
            appeal.setBusinessPhone(dto.getBusinessPhone());
            appeal.setProvince(dto.getProvince());
            appeal.setCity(dto.getCity());
            appeal.setCounty(dto.getCounty());
            appeal.setStreet(dto.getStreet());
            appeal.setDuty(dto.getDuty());
            appeal.setBusinessRealname(dto.getBusinessRealname());
            this.save(appeal);
        }
     }

    /**
     * 修改诉求
     * @param dto
     * @param loginUserId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAppeal(GxmhAppealParamDto dto, String loginUserId) {
        this.checkParam(dto);
        if(StrUtil.isEmpty(dto.getBaseId())) {
            throw new BusinessException("诉求标识为空");
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginUserId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        this.checkAdminParam(dto, sysUserDto.getUsername());
        GxmhAppeal appeal = new GxmhAppeal();
        appeal.setBaseId(dto.getBaseId());
        appeal.setDeptName(dto.getDeptName());
        appeal.setBaseUpdateBy(loginUserId);
        appeal.setBusinessPhone(dto.getBusinessPhone());
        appeal.setDuty(dto.getDuty());
        appeal.setBusinessRealname(dto.getBusinessRealname());
        if(GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            appeal.setProvince(dto.getProvince());
            appeal.setCity(dto.getCity());
            appeal.setCounty(dto.getCounty());
            if(StrUtil.isBlank(dto.getStreet())) {
                appeal.setStreet(null);
            }else {
                appeal.setStreet(dto.getStreet());
            }
        }else {
            appeal.setProvince(sysUserDto.getProvince());
            appeal.setCity(sysUserDto.getCity());
            appeal.setCounty(sysUserDto.getRegion());
            appeal.setStreet(sysUserDto.getStreet());
        }
        if(StrUtil.isNotEmpty(dto.getBusinessUsername())) {
            appeal.setBusinessUsername(dto.getBusinessUsername());
            // 1. 查寻输入账号的userId
            SysUserDto sysUser = this.baseMapper.queryUserIdByUsername(dto.getBusinessUsername());
            if (sysUser == null) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】不存在");
            }
            appeal.setUserId(sysUser.getBaseId());
            appeal.setUserMobile(sysUser.getMobile());
            // 2. 查询输入账号绑定的企业
            String userEnterpriseId = this.baseMapper.queryEnterpriseIdByUserId(sysUser.getBaseId());
            if (StrUtil.isEmpty(userEnterpriseId)) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】未绑定企业");
            }
            // 3. 判断该企业是否是政府
            Integer zfCount = this.baseMapper.queryZFCountByEnterpriseId(userEnterpriseId);
            if (zfCount == 0) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】所属企业不是政府部门");
            }
            appeal.setEnterpriseId(userEnterpriseId);
            // 3. 查询该用户是否开通过名片
            Integer cardCount = this.baseMapper.queryCardountByUserId(sysUser.getBaseId());
            if (cardCount == 0) {
                throw new BusinessException("该用户【" + dto.getBusinessUsername() + "】未开通名片");
            }
        }
        this.baseMapper.updateAppeal(appeal, loginUserId);
    }

    /**
     * 根据id查询诉求
     * @param baseId
     * @return
     */
    @Override
    public GxmhAppealListItemVo queryAppealById(String baseId) {
        GxmhAppeal gxmhAppeal = this.baseMapper.selectById(baseId);
        if(gxmhAppeal == null) {
            throw new BusinessException("该诉求不存在");
        }
        GxmhAppealListItemVo vo = new GxmhAppealListItemVo();
        vo.setBaseId(gxmhAppeal.getBaseId());
        vo.setDeptName(gxmhAppeal.getDeptName());
        vo.setBusinessUsername(gxmhAppeal.getBusinessUsername());
        vo.setBusinessPhone(gxmhAppeal.getBusinessPhone());
        vo.setDuty(gxmhAppeal.getDuty());
        vo.setBusinessRealname(gxmhAppeal.getBusinessRealname());
        vo.setProvince(gxmhAppeal.getProvince());
        vo.setCity(gxmhAppeal.getCity());
        vo.setCounty(gxmhAppeal.getCounty());
        vo.setStreet(gxmhAppeal.getStreet());
        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeAppreal(List<String> baseIdList) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        this.baseMapper.removeAppreal(baseIdList);
    }

     private void checkParam(GxmhAppealParamDto dto) {

        if(StrUtil.isBlank(dto.getDeptName())) {
            throw new BusinessException("请填写部门名称");
        }
        if(StrUtil.isBlank(dto.getBusinessPhone())) {
            throw new BusinessException("请填写手机号");
        }
     }

     private void checkAdminParam(GxmhAppealParamDto dto, String loginUsername) {
        if(GxmhConstant.ADMIN_USER_NAME.equals(loginUsername)) {
            if(StrUtil.isBlank(dto.getProvince())) {
                throw new BusinessException("管理员账号添加数据时需指定数据所属区域");
            }
            if(StrUtil.isBlank(dto.getCity())) {
                throw new BusinessException("管理员账号添加数据时需指定数据所属区域");
            }
            if(StrUtil.isBlank(dto.getCounty())) {
                throw new BusinessException("管理员账号添加数据时需指定数据所属区域");
            }
        }
     }

}
